package com.huitone.gddw.service.impl.monitoring;


import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;

import com.huitone.gddw.common.excel.CreateExcel;

import com.huitone.gddw.dao.entity.AlarmReceiveUser;
import com.huitone.gddw.dao.entity.HostInterface;
import com.huitone.gddw.dao.entity.Index;
import com.huitone.gddw.dao.entity.InnormalEvent;
import com.huitone.gddw.dao.entity.MainItem;
import com.huitone.gddw.dao.entity.ObjItem;
import com.huitone.gddw.dao.entity.ObjItemProperty;
import com.huitone.gddw.dao.entity.ObjectManagement;
import com.huitone.gddw.dao.entity.ReturnedValue;

import com.huitone.gddw.dao.entity.Trigger;
import com.huitone.gddw.dao.monitoring.ObjectItemDao;
import com.huitone.gddw.service.MainItemService;


import com.huitone.gddw.utils.MonitoringResult;
import com.huitone.gddw.utils.MonitoringUtils;
import com.huitone.gddw.utils.StringUtils;

import net.sf.json.JSONArray;
/**
 * 主监控的服务层
 * @author lipengfei
 *
 */
import net.sf.json.JSONObject;
@Service("mainService")
public class MainItemServiceImpl implements MainItemService {
	@Resource
	ObjectItemDao  objDao;
	
	/**
	 * 获取主监控的对象信息
	 */
	@Override
	public MonitoringResult<List<MainItem>> loadMainItem(ReturnedValue value) {
		//用于传递数据结果的方法
		MonitoringResult<List<MainItem>> result = new MonitoringResult<List<MainItem>>();
				
		//用于存放MainItem对象的集合
		List<MainItem> mainList = new ArrayList<MainItem>();
						
		//传入搜索条件，在数据库全部对象表中查找host类型的数据
		Map<String, Object> map = MonitoringUtils.getMap(value.getPageNo(),value.getPageSize());
		map.put("objType","host");
		map.put("startTime", value.getStartTime());
		map.put("endTime", value.getEndTime());
		map.put("hostName", value.getHostName());
		List<ObjectManagement> objList = objDao.selectObjAllByObjType(map);
		System.out.println(objList);
		if(!objList.isEmpty()){
			for(ObjectManagement obj:objList){
				HostInterface inter= objDao.selectIPByObjId(obj.getObjId());
				if(inter!=null){
					Map<String, String> itemMap = new HashMap<String, String>(); 
					itemMap.put("objId", obj.getObjId());
					itemMap.put("interfaceId", inter.getInterfaceId());
					//包装传送对象
					MainItem mainItem = new MainItem();
					String id = MonitoringUtils.saveId(obj.getObjId(),inter.getInterfaceId());
					mainItem.setId(id);
					mainItem.setTime(obj.getInsertTime());
					mainItem.setMainName(obj.getObjName());
					mainItem.setMainIp(inter.getHostIp());
					mainItem.setNowExceptionEventCount(StringUtils.intToString(objDao.getNowExcptionCount(itemMap)));
					mainItem.setAllExceptionEventCount(StringUtils.intToString(objDao.getAllExcptionCount(itemMap)));
					AlarmReceiveUser user = objDao.getAlarmReceiveUser(itemMap);
					if(user!=null){
						mainItem.setMonitorHead(user.getReceiveUser());
						mainItem.setPhone(user.getPhone());
						mainItem.setEmail(user.getEmail());
					}
					mainItem.setPurpose(inter.getRemark());
					mainList.add(mainItem);
				}else{
					MainItem mainItem = new MainItem();
					String id = MonitoringUtils.saveId(obj.getObjId(),"");
					mainItem.setId(id);
					mainItem.setTime(obj.getInsertTime());
					mainItem.setMainName(obj.getObjName());
					mainList.add(mainItem);
				}
			}
			//包装结果集
			result.setStatus(0);
			result.setMsg("主机监控信息加载成功");
			result.setData(mainList);
			result.setPageNo(value.getPageNo());
			result.setPageSize((value.getPageSize()));
			result.setTotalCount(objDao.selectObjCountByType(map));
		}else{
			result.setMsg("没有监控对象");
		}
		
		return result;
	}
	/**
	 * 获取指标信息的方法
	 * @return	主机总监控对象
	 */
	@Override
	public MonitoringResult<Map<String, Object>> addIndex() {
		//用于传递数据结果的方法
		MonitoringResult<Map<String, Object>> result = new MonitoringResult<Map<String, Object>>();
		//用于存放结果数据
		Map<String, Object> resultMap = new HashMap<String, Object>();
		//存放搜索所用的参数
		Map<String, String> map = new HashMap<>();
		map.put("objType","host");
		//主机名称集合
		List<ObjectManagement> hostNameList = new ArrayList<ObjectManagement>();
		List<ObjectManagement> objList = objDao.selectObjName(map);
		if(!objList.isEmpty()){
			for(ObjectManagement obj:objList){
				HostInterface inter= objDao.selectIPByObjId(obj.getObjId());
				if(inter!=null){
					String id = MonitoringUtils.saveId(obj.getObjId(),inter.getInterfaceId());
					obj.setObjId(id);
				}else{
					String id = MonitoringUtils.saveId(obj.getObjId(),"");
					obj.setObjId(id);
				}
			}
			hostNameList.addAll(objList);
		}else{
			result.setMsg("没有监控主机");
		}
		//封装结果集
		result.setStatus(0);
		result.setMsg("主机名称获取成功");
		resultMap.put("hostnames", hostNameList);
		result.setData(resultMap);
		return result;
	}
	@Override
	public MonitoringResult<Map<String, Object>> showIndex(ReturnedValue value) {
		//用于传递数据结果的方法
		MonitoringResult<Map<String, Object>> result = new MonitoringResult<Map<String, Object>>();
		//用于存放结果数据
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		String [] ids = MonitoringUtils.getId(value.getHostId());  
		//保存需要的参数
		Map<String, String> map = new HashMap<>();
		map.put("objId", ids[0]);
		map.put("interfaceId", ids[1]);
		List<ObjItemProperty> indexnamelist = new ArrayList<ObjItemProperty>();
		List<AlarmReceiveUser> alarmUserList = objDao.selectAlarmReceiveUser(ids[0]);
		List<ObjItem> objItemlist = objDao.selectObjItemById(map);
		if(!objItemlist.isEmpty()){
			for(ObjItem objItem:objItemlist){
				List<ObjItemProperty> indexname = objDao.getIndexName(objItem.getItemId());
				indexnamelist.addAll(indexname);
			}
			result.setStatus(0);
			result.setMsg("主机监控指标名称获取成功,告警接收人获取成功");
		}else{
			result.setMsg("没有获取到该主机的指标或者指标信息都已添加");
		}
		resultMap.put("indexnames", indexnamelist);
		resultMap.put("alarmusers", alarmUserList);
		result.setData(resultMap);
		System.out.println(result);
		return result;
	}
	@Override
	public MonitoringResult<MainItem> save(ReturnedValue value) {
		//用于传递数据结果的方法
		MonitoringResult<MainItem> result = new MonitoringResult<MainItem>();
		try {
			if(value.getIndex()!=null && value.getAlarmRecUser()!=null){
				JSONArray indexja =JSONArray.fromObject(URLDecoder.decode(value.getIndex(),"UTF-8")); 
				JSONArray alarmja = JSONArray.fromObject(URLDecoder.decode(value.getAlarmRecUser(),"UTF-8"));
					for(int i = 0;i< indexja.size();i++){
						JSONObject indexjb = indexja.getJSONObject(i);
								if(!indexjb.getString("alarmLevel").isEmpty()){
									//保存指标信息
									ObjItemProperty objItemProperty = new ObjItemProperty();
									objItemProperty.setKeyId(indexjb.getString("keyId"));
									if(!indexjb.getString("quantity").isEmpty()){
										objItemProperty.setQuantity(StringUtils.strToDouble(indexjb.getString("quantity")));
									}
									objItemProperty.setIndexUnit(indexjb.getString("unit"));
									objDao.updateIndex(objItemProperty);
									//保存告警信息
									Trigger trigger = new Trigger();
									String triggerId = StringUtils.uuid();
									trigger.setTriggerId(triggerId);
									trigger.setItemId(objDao.selectItemIdByKeyId(indexjb.getString("keyId")));
									trigger.setKeyId(indexjb.getString("keyId"));
									if(!indexjb.getString("upperLimit").isEmpty()){
										trigger.setUpperLimit(StringUtils.strToDouble(indexjb.getString("upperLimit")));
									}
									if(!indexjb.getString("lowerLimit").isEmpty()){
										trigger.setLowerLimit(StringUtils.strToDouble(indexjb.getString("lowerLimit")));
										
									}
									trigger.setAlarmLevel(StringUtils.strToInteger(indexjb.getString("alarmLevel")));
									trigger.setSustainTime(indexjb.getString("sustainTime"));
									objDao.saveAlarm(trigger);
									//保存告警接受人
									for(int j = 0;j<alarmja.size();j++){
										JSONObject alarmjb = alarmja.getJSONObject(j);
										AlarmReceiveUser user = new AlarmReceiveUser();
										user.setRceId(alarmjb.getString("rceId"));
										user.setPhone(alarmjb.getString("phone"));
										user.setEmail(alarmjb.getString("email"));
										user.setUserType(alarmjb.getString("userType"));
										user.setRecAlarmLevel1(alarmjb.getString("recAlarmLevel1"));
										
										user.setRecAlarmLevel2(alarmjb.getString("recAlarmLevel2"));
										
										user.setRecAlarmLevel3(alarmjb.getString("recAlarmLevel3"));
										
										objDao.updateUser(user);
									}
									
							}else{
								result.setMsg("必须添加告警信息");
								return result;
							}
						}
					result.setStatus(0);
					result.setMsg("保存成功");
					return result;

				}else{
					result.setMsg("监控指标或接收人不能为空,保存失败");
				}
			
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("保存失败");
		}
		return result;
	}
	
	
	@Override
	public MonitoringResult<Map<String, Object>> updata(ReturnedValue value) {
		//用于传递数据结果的方法
		MonitoringResult<Map<String, Object>> result = new MonitoringResult<Map<String, Object>>();
		
		String ids[] = MonitoringUtils.getId(value.getHostId());
		//存放参数
		Map<String, String> map = new HashMap<>();
		map.put("objId",ids[0]);
		map.put("interfaceId",ids[1]);
		//用于存储数据结果map
		Map<String, Object> mainMap = new HashMap<>();
		//存放指标的集合
		List<Index> indexList = new ArrayList<Index>();
		//存放告警接受人的集合
		List<AlarmReceiveUser> userList =new ArrayList<AlarmReceiveUser>();
		
		List<ObjItem> objItemlist = objDao.selectObjItemById(map);
		if(!objItemlist.isEmpty()){
			for(ObjItem objItem:objItemlist){
				List<Index> objProperty = objDao.selectIndex(objItem.getItemId());
				indexList.addAll(objProperty);
			}
			List<AlarmReceiveUser> recList = objDao.selectAlarmReceiveUser(ids[0]);
			userList.addAll(recList);
			result.setStatus(0);
			result.setMsg("主机监控指标信息获取成功");
			mainMap.put("index", indexList);
			mainMap.put("receiver", userList);
			result.setData(mainMap);
		}else{	
				result.setMsg("该主机还没添加指标监控");
		}	
		return result;
	}
	
	@Override											
	public MonitoringResult<MainItem> createExcel(HttpServletResponse response,ReturnedValue value) {
		//用于传递数据结果的方法
		MonitoringResult<MainItem> result = new MonitoringResult<MainItem>();
						
		//用于存放MainItem对象的集合
		List<MainItem> mainList = new ArrayList<MainItem>();
		
		String fileName = "环境监控-主机总监控表";

		//在数据库全部对象表中查找host类型的数据
		Map<String, String> map = new HashMap<String, String>();
		map.put("objType","host");
		map.put("startTime", value.getStartTime());
		map.put("endTime", value.getEndTime());
		map.put("hostName", value.getHostName());
		List<ObjectManagement> objList = objDao.selectObjName(map);
		if(!objList.isEmpty()){
			for(ObjectManagement obj:objList){
				HostInterface inter= objDao.selectIPByObjId(obj.getObjId());
				if(inter!=null){
					Map<String, String> itemMap = new HashMap<String, String>(); 
					itemMap.put("objId", obj.getObjId());
					itemMap.put("interfaceId", inter.getInterfaceId());
					//包装传送对象
					MainItem mainItem = new MainItem();
					String id = MonitoringUtils.saveId(obj.getObjId(),inter.getInterfaceId());
					mainItem.setId(id);
					mainItem.setTime(obj.getInsertTime());
					mainItem.setMainName(obj.getObjName());
					mainItem.setMainIp(inter.getHostIp());
					mainItem.setNowExceptionEventCount(StringUtils.intToString(objDao.getNowExcptionCount(itemMap)));
					mainItem.setAllExceptionEventCount(StringUtils.intToString(objDao.getAllExcptionCount(itemMap)));
					AlarmReceiveUser user = objDao.getAlarmReceiveUser(itemMap);
					if(user!=null){
						mainItem.setMonitorHead(user.getReceiveUser());
						mainItem.setPhone(user.getPhone());
						mainItem.setEmail(user.getEmail());
					}
					mainItem.setPurpose(inter.getRemark());
					mainList.add(mainItem);
				}else{
					MainItem mainItem = new MainItem();
					String id = MonitoringUtils.saveId(obj.getObjId(),"");
					mainItem.setId(id);
					mainItem.setTime(obj.getInsertTime());
					mainItem.setMainName(obj.getObjName());
					mainList.add(mainItem);
				}
			}
		}else{
			result.setMsg("没有监控对象");
		}
		HSSFWorkbook wb = (HSSFWorkbook)CreateExcel
				.getInstance()
				.CreateNewExcelNoTemplate(fileName, mainList).getWorkbook();
		  
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		     		
		//对数据结果进行包装传送
		OutputStream fOut = null;    
	        try {
	        	response.reset();
	            fileName = new String(fileName.getBytes("gbk"), "ISO8859-1");
	            response.setContentType("application/x-msdownload");    
	            response.setHeader("Content-Disposition", "attachment; filename="+fileName+sdf.format(new Date())+".xls");    
	            fOut = response.getOutputStream();
	            wb.write(fOut); 
	            result.setStatus(0);
	    		result.setMsg("表格导出成功");
	        } catch (Exception e) {    
	            e.printStackTrace(); 
	            
	            result.setStatus(1);
	    		result.setMsg("表格导出失败");
	        } finally {      
	            try {
	            	fOut.flush();
	            	fOut.close();      
	            } catch (IOException e) {      
	                e.printStackTrace();    
	            }      
	        } 
	        
	    return result;
	}
	@Override
	public MonitoringResult<Map<String, Object>> showExe(ReturnedValue value) {
		// TODO Auto-generated method stub
		//用于传递数据结果的方法
		MonitoringResult<Map<String, Object>> result = new MonitoringResult<Map<String, Object>>();
		//用于存储数据结果map
		Map<String, Object> mainMap = new HashMap<>();
		String [] ids = MonitoringUtils.getId(value.getHostId());
		//存放参数
		Map<String, String> map = new HashMap<>();
		map.put("objId", ids[0]);
		map.put("interfaceId", ids[1]);
		//存放异常信息的集合
		List<InnormalEvent> eventList = new ArrayList<InnormalEvent>();
		List<InnormalEvent> allEventList = new ArrayList<InnormalEvent>();
		List<InnormalEvent> innorList = objDao.getNowExcptionInfo(map);
		List<InnormalEvent> allInnorList = objDao.getAllExcptionInfo(map);
		eventList.addAll(innorList);
		allEventList.addAll(allInnorList);
		result.setStatus(0);
		result.setMsg("异常信息获取成功");
		mainMap.put("nowEvent", eventList);
		mainMap.put("allEvent", allEventList);
		result.setData(mainMap);
		return result;
	}
	@Override
	public MonitoringResult<MainItem> updataSave(ReturnedValue value) {
		//用于传递数据结果的方法
		MonitoringResult<MainItem> result = new MonitoringResult<MainItem>();
		try {
			if(value.getIndex()!=null && value.getAlarmRecUser()!=null){
			JSONArray indexja =JSONArray.fromObject(URLDecoder.decode(value.getIndex(),"UTF-8")); 
			JSONArray alarmja = JSONArray.fromObject(URLDecoder.decode(value.getAlarmRecUser(),"UTF-8"));
				for(int i = 0;i< indexja.size();i++){
					JSONObject indexjb = indexja.getJSONObject(i);
					if(!indexjb.getString("alarmLevel").isEmpty()){
						//保存指标信息
						ObjItemProperty objItemProperty = new ObjItemProperty();
						objItemProperty.setKeyId(indexjb.getString("keyId"));
						if(!indexjb.getString("quantity").isEmpty()){
							objItemProperty.setQuantity(StringUtils.strToDouble(indexjb.getString("quantity")));
						}
						objItemProperty.setIndexUnit(indexjb.getString("unit"));
						objDao.updateIndex(objItemProperty);
						//保存告警信息
						Trigger trigger = new Trigger();
						trigger.setTriggerId(indexjb.getString("triggerId"));
						trigger.setItemId(objDao.selectItemIdByKeyId(indexjb.getString("keyId")));
						trigger.setKeyId(indexjb.getString("keyId"));
						if(!indexjb.getString("upperLimit").isEmpty()){
								trigger.setUpperLimit(StringUtils.strToDouble(indexjb.getString("upperLimit")));
						}
						if(!indexjb.getString("lowerLimit").isEmpty()){
								trigger.setLowerLimit(StringUtils.strToDouble(indexjb.getString("lowerLimit")));
												
						}
						trigger.setAlarmLevel(StringUtils.strToInteger(indexjb.getString("alarmLevel")));
						trigger.setSustainTime(indexjb.getString("sustainTime"));
						objDao.updateAlarm(trigger);
						//保存告警接受人
						for(int j = 0;j<alarmja.size();j++){
							JSONObject alarmjb = alarmja.getJSONObject(j);
							System.out.println(alarmjb);
							AlarmReceiveUser user = new AlarmReceiveUser();
							user.setRceId(alarmjb.getString("rceId"));
							user.setPhone(alarmjb.getString("phone"));
							user.setEmail(alarmjb.getString("email"));
							user.setUserType(alarmjb.getString("userType"));
							user.setRecAlarmLevel1(alarmjb.getString("recAlarmLevel1"));
							
							user.setRecAlarmLevel2(alarmjb.getString("recAlarmLevel2"));
							
							user.setRecAlarmLevel3(alarmjb.getString("recAlarmLevel3"));
							
							System.out.println(user);	
							objDao.updateUser(user);
							
							}
											
							}else{
									result.setMsg("必须添加告警信息");
									return result;
							}
						}
							result.setStatus(0);
							result.setMsg("保存成功");
							return result;

						}else{
							result.setMsg("监控指标或接收人不能为空,保存失败");
						}
					
				} catch (Exception e) {
					e.printStackTrace();
					result.setMsg("保存失败");
				}
				return result;
	}
	


}
